package com.tiyende.kash.loop.ui.popupwindow

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.common.adapter.CommonOnItemChildClickListener
import com.lib.common.adapter.CommonRecyclerViewAdapter
import com.lib.common.adapter.CommonViewHolderHelper
import com.lib.common.shapeview.layout.ShapeLinearLayout
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.TiyendeApp
import com.tiyende.kash.loop.base.popup.XGravity
import com.tiyende.kash.loop.base.popup.YGravity
import com.tiyende.kash.loop.common.CommonPopup
import com.tiyende.kash.loop.databinding.TiyendePopupwindowCommonBinding
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/10/22 14:46
 * @Annotation：列表选择
 */
class TiyendeCommonPopupwindow(val context: Context) {
    lateinit var binding: TiyendePopupwindowCommonBinding
    //开始选择时间
    private var startTime = 0L;

    /* 筛选框宽度，默认屏幕宽度 */
    var popupWidth = TiyendeApp.app.getPhoneWidth()
    //选中的item
    var selectItem: JSONObject? = null

    private var mItemListener: IItemClickListener? = null

    interface IItemClickListener {
        fun onConfirmAction(data: JSONObject?)
        fun onDismissListener()
    }
    private var mEasyPopup: CommonPopup? = null

    //分类
    private var mAdapter: SelectItemAdapter? = null

    fun show(view: View, dimView: ViewGroup) {
        startTime = System.currentTimeMillis()
        if (mEasyPopup == null) {
            showViewDown(view, dimView)
        } else {
            mEasyPopup?.showAtAnchorView(view, YGravity.BELOW, XGravity.CENTER, 0, 0)
        }
    }

    /* 选择回调 */
    fun setSelectItemListener(listener: IItemClickListener?) {
        mItemListener = listener
    }

    /* 设置宽度 */
    fun setWindowWidth(width: Int){
        this.popupWidth = width
    }

    /* 设置分类数据 */
    fun setBrandList(list: List<JSONObject>) {
        this.mAdapter?.data = list
    }

    private fun showViewDown(view: View, dimView: ViewGroup) {
        mEasyPopup = CommonPopup(context)
        binding = TiyendePopupwindowCommonBinding.inflate(LayoutInflater.from(context))
        mEasyPopup?.setContentView(binding.root)
        mEasyPopup?.width = this.popupWidth
//        mEasyPopup?.height = Apps.getPhoneHeight() / 2
        mEasyPopup?.setAnimationStyle(R.style.popup_anim)
        //是否允许点击PopupWindow之外的地方消失
        mEasyPopup?.setFocusAndOutsideEnable(true)
        //允许背景变暗
        mEasyPopup?.setBackgroundDimEnable(false)
        //变暗的透明度(0-1)，0为完全透明
        mEasyPopup?.setDimValue(0.4f)
        //变暗的背景颜色
        mEasyPopup?.setDimColor(Color.BLACK)
        //指定任意 ViewGroup 背景变暗
        mEasyPopup?.setDimView(dimView)
//        mEasyPopup?.apply();
        CommonPopup.create()
        mEasyPopup?.showAtAnchorView(view, YGravity.BELOW, XGravity.CENTER, 0, 0)
        //排序列表
        initRecyclerView()
        mEasyPopup?.setOnDismissListener { // popupWindow隐藏时恢复屏幕正常透明度
            if (mItemListener != null) {
                mItemListener?.onDismissListener()
            }
        }
    }

    private fun initRecyclerView() {
        binding.selectListView.layoutManager = LinearLayoutManager(context)
        this.mAdapter = SelectItemAdapter( binding.selectListView)
        binding.selectListView.adapter = this.mAdapter
        binding.selectListView.itemAnimator = DefaultItemAnimator()
        this.mAdapter?.setOnItemChildClickListener(onItemClickListener()) //点击
    }

    /* RecyclerView点击Item */
    internal inner class onItemClickListener: CommonOnItemChildClickListener {
        @SuppressLint("NotifyDataSetChanged")
        override fun onItemChildClick(parent: ViewGroup, childView: View, position: Int) {
            val model = mAdapter?.getItem(position)
            model?.let {
                if (childView.id == R.id.itemLayout) {
                    mAdapter?.let { adapter ->
                        for (brandItem in adapter.data) {
                            brandItem.put("isSelect",false)
                            if (brandItem?.optString("title") == it.optString("title")) {
                                brandItem.put("isSelect",true)
                            }
                        }
                    }
                    mAdapter?.notifyDataSetChanged()
                    if (mItemListener != null) {
                        it.put("duration",System.currentTimeMillis() - startTime)
                        mItemListener?.onConfirmAction(it)
                        mEasyPopup?.dismiss()
                    }
                }
            }
        }
    }

    internal inner class SelectItemAdapter(recyclerView: RecyclerView?) : CommonRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.tiyende_popupwindow_common_item) {
        override fun setItemChildListener(helper: CommonViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.itemLayout) //点击Item
        }
        override fun fillData(helper: CommonViewHolderHelper, position: Int, model: JSONObject) {
            val textTitle = helper.getTextView(R.id.textTitle)
            textTitle.text = model.optString("title")

            val itemLayout = helper.getView<ShapeLinearLayout>(R.id.itemLayout)
            if (model.optBoolean("isSelect",false)) {
                helper.setVisibility(R.id.imgStatus,View.VISIBLE)
                if (position == itemCount - 1){
                    itemLayout.shapeDrawableBuilder
                        .setSolidColor(Color.parseColor("#ffcdf2f3"))
                        .setBottomLeftRadius(TiyendeApp.app.resources.getDimension(com.lib.common.R.dimen.dp_12))
                        .setBottomRightRadius(TiyendeApp.app.resources.getDimension(com.lib.common.R.dimen.dp_12))
                        .intoBackground()
                } else {
                    itemLayout.shapeDrawableBuilder
                        .setSolidColor(Color.parseColor("#ffcdf2f3"))
                        .setBottomLeftRadius(TiyendeApp.app.resources.getDimension(com.lib.common.R.dimen.dp_0))
                        .setBottomRightRadius(TiyendeApp.app.resources.getDimension(com.lib.common.R.dimen.dp_0))
                        .intoBackground()
                }
            } else {
                helper.setVisibility(R.id.imgStatus,View.INVISIBLE)
                itemLayout.shapeDrawableBuilder.setSolidColor(Color.parseColor("#00000000")).intoBackground()
            }
            if (position == itemCount - 1){
                helper.setVisibility(R.id.viewLine,View.INVISIBLE)
            } else {
                helper.setVisibility(R.id.viewLine,View.VISIBLE)
            }
        }
    }
}